<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>历史记录 - 试验检测系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#6366f1',
                        secondary: '#8b5cf6',
                        accent: '#06b6d4'
                    }
                }
            }
        }
    </script>
</head>

<body class="bg-white min-h-screen p-4">
    <div class="max-w-md w-full mx-auto bg-white rounded-3xl shadow-xl overflow-hidden border border-gray-200">
        <!-- Header -->
        <div class="bg-gradient-to-r from-blue-500 to-indigo-600 p-6 text-white text-center">
            <h1 class="text-2xl font-bold">历史记录</h1>
            <p class="text-blue-100 mt-1">委托历史记录列表</p>
        </div>

        <!-- Content -->
        <div class="p-6">
            <!-- Status Filter -->
            <div class="mb-6">
                <h2 class="text-lg font-semibold text-gray-800 mb-3">状态筛选</h2>
                <div class="grid grid-cols-2 gap-2">
                    <button id="filter-all"
                        class="py-2 px-3 bg-blue-100 text-blue-700 rounded-lg text-sm font-medium">全部</button>
                    <button id="filter-SUBMITTED"
                        class="py-2 px-3 bg-gray-100 text-gray-700 rounded-lg text-sm font-medium">正在等待处理</button>
                    <button id="filter-GAINED"
                        class="py-2 px-3 bg-gray-100 text-gray-700 rounded-lg text-sm font-medium">待签字</button>
                    <button id="filter-EXECUTING"
                        class="py-2 px-3 bg-gray-100 text-gray-700 rounded-lg text-sm font-medium">检测中</button>
                    <button id="filter-RETURNED"
                        class="py-2 px-3 bg-gray-100 text-gray-700 rounded-lg text-sm font-medium">已退回</button>
                    <button id="filter-COMPLETED"
                        class="py-2 px-3 bg-gray-100 text-gray-700 rounded-lg text-sm font-medium">已完成</button>
                </div>
            </div>

            <!-- Loading Indicator -->
            <div id="loading" class="text-center py-8">
                <div class="inline-flex items-center">
                    <svg class="animate-spin -ml-1 mr-3 h-5 w-5 text-blue-500" xmlns="http://www.w3.org/2000/svg"
                        fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4">
                        </circle>
                        <path class="opacity-75" fill="currentColor"
                            d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z">
                        </path>
                    </svg>
                    <span>加载中...</span>
                </div>
            </div>

            <!-- Error Message -->
            <div id="error-message" class="hidden bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
                <p id="error-text">无法加载数据，请检查网络连接或稍后重试。</p>
            </div>

            <!-- Order List -->
            <div id="order-list" class="space-y-4 hidden">
                <!-- 订单项将由JavaScript动态生成 -->
            </div>

            <!-- Status Legend -->
            <div class="mt-8 pt-6 border-t border-gray-200">
                <h3 class="font-semibold text-gray-800 mb-3">状态说明</h3>
                <div class="grid grid-cols-2 gap-3">
                    <div class="flex items-center">
                        <div class="w-3 h-3 bg-yellow-500 rounded-full mr-2"></div>
                        <span class="text-sm text-gray-600">正在等待处理</span>
                    </div>
                    <div class="flex items-center">
                        <div class="w-3 h-3 bg-blue-500 rounded-full mr-2"></div>
                        <span class="text-sm text-gray-600">待签字</span>
                    </div>
                    <div class="flex items-center">
                        <div class="w-3 h-3 bg-purple-500 rounded-full mr-2"></div>
                        <span class="text-sm text-gray-600">待检测</span>
                    </div>
                    <div class="flex items-center">
                        <div class="w-3 h-3 bg-green-500 rounded-full mr-2"></div>
                        <span class="text-sm text-gray-600">报告已出</span>
                    </div>
                </div>
            </div>

            <!-- Action Buttons -->
            <div class="flex flex-col gap-3 mt-6">
                <button onclick="location.href='index.html'"
                    class="bg-gradient-to-r from-blue-500 to-indigo-600 text-white py-3 px-4 rounded-lg font-semibold shadow-lg hover:shadow-xl transform hover:-translate-y-0.5 transition-all duration-300">
                    <i class="fas fa-home mr-2"></i> 返回首页
                </button>
            </div>
        </div>
    </div>

    <script>
        // API端点
        const API_URL = 'http://8.137.148.120:28081/order/get-my-orders';

        // 解析URL参数
        let phoneNumber
        const urlParams = new URLSearchParams(window.location.search);
        console.log('urlParams', urlParams.get('phone'), localStorage.getItem('userPhone'));
        if (urlParams.size == 0) {
            phoneNumber = localStorage.getItem('userPhone')
        } else {
            phoneNumber = urlParams.get('phone');
        }
        // 获取phone参数值

        // 请求参数
        const REQUEST_PARAMS = {
            user: phoneNumber,
            additionalFields: ['jcxm', 'wtdw', 'ypmc', 'wtsj', 'sybh'],
            status: ''
        };
        // 状态映射
        const STATUS_MAP = {
            'SUBMITTED': { text: '正在等待处理', class: 'bg-yellow-500' },
            'GAINED': { text: '待签字', class: 'bg-blue-500' },
            'test': { text: '检测中', class: 'bg-purple-500' },
            'completed': { text: '报告已出', class: 'bg-green-500' },
            'RETURNED': { text: '已退回', class: 'bg-green-500' },
        };

        // 字段映射（将API返回的字段映射到前端使用的字段）
        const FIELD_MAP = {
            'jcxm': 'jcxm',
            'wtdw': 'wtdw',
            'ypmc': 'ypmc',
            'wtsj': 'wtsj',
            'sybh': 'sybh'
        };

        // 全局变量存储所有订单和当前筛选状态
        let allOrders = [];
        let currentFilter = 'all';

        // DOM元素
        const orderListElement = document.getElementById('order-list');
        const loadingElement = document.getElementById('loading');
        const errorElement = document.getElementById('error-message');
        const errorTextElement = document.getElementById('error-text');

        // 页面加载时获取数据
        document.addEventListener('DOMContentLoaded', function () {
            fetchOrders();
            setupFilterButtons();
        });

        //遍历找到字段对应值
        function getFieldValuesObject(fieldValues, fieldNames) {
            const result = {};
            // 先创建所有目标字段的键，初始值为null
            fieldNames.forEach(fieldName => {
                result[fieldName] = "";
            });
            // 遍历fieldValues，为存在的字段赋值
            fieldValues.forEach(item => {
                if (fieldNames.includes(item.fieldName)) {
                    result[item.fieldName] = item.value;
                }
            });
            return result;
        }

        // 获取订单数据
        async function fetchOrders() {
            try {
                showLoading();

                // 构建URL参数
                const params = new URLSearchParams();
                console.log('');

                params.append('user', REQUEST_PARAMS.user);
                // params.append('additionalFields', JSON.stringify(REQUEST_PARAMS.additionalFields));
                REQUEST_PARAMS.additionalFields.forEach(field => {
                    params.append('additionalFields', field);
                });

                const url = `${API_URL}?${params.toString()}`;
                
                const response = await fetch(url);
                console.log('url',response);
                if (!response.status) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }

                const data = await response.json();

                // 处理API返回的数据
                if (data && data.success) {
                    console.log('data', data);

                    // 转换字段名称
                    allOrders = data.data.data.map(item => {
                        let convertedItem = { status: item.status, materialCode: item.materialCode, submitTime:item.submitTime };
                        convertedItem = { ...getFieldValuesObject(item.fieldValues, REQUEST_PARAMS.additionalFields), ...convertedItem }
                        // 转换additionalFields中的字段
                        REQUEST_PARAMS.additionalFields.forEach(field => {
                            const frontendField = FIELD_MAP[field];
                            if (frontendField) {
                                // // convertedItem[frontendField] = item.fieldValues.fieldName == field ? item.fieldValues.value : ''
                                // item.fieldValues.find((ite) => {
                                //     console.log('ite', ite.fieldName);
                                //     convertedItem[frontendField] = ite.fieldName == field ? ite.value : ''
                                // })
                            }
                        });

                        return convertedItem;
                    });
                    console.log('allOrders', allOrders);

                    hideLoading();
                    renderOrders(allOrders);
                } else {
                    throw new Error(data.message || 'API返回数据格式不正确');
                }
            } catch (error) {
                console.error('获取数据失败:', error);
                hideLoading();
                showError(error.message || '无法加载数据，请检查网络连接或稍后重试。');
            }
        }

        // 设置筛选按钮事件
        function setupFilterButtons() {
            document.getElementById('filter-all').addEventListener('click', () => filterOrders('all'));
            document.getElementById('filter-SUBMITTED').addEventListener('click', () => filterOrders('SUBMITTED'));
            document.getElementById('filter-GAINED').addEventListener('click', () => filterOrders('GAINED'));
            document.getElementById('filter-EXECUTING').addEventListener('click', () => filterOrders('EXECUTING'));
            document.getElementById('filter-RETURNED').addEventListener('click', () => filterOrders('RETURNED'));
            document.getElementById('filter-COMPLETED').addEventListener('click', () => filterOrders('COMPLETED'));
        }

        // 筛选订单
        async function filterOrders(status) {
            currentFilter = status;
            REQUEST_PARAMS.status = status
            await fetchOrders()
            // 更新按钮样式
            document.querySelectorAll('[id^="filter-"]').forEach(button => {
                button.classList.remove('bg-blue-100', 'text-blue-700');
                button.classList.add('bg-gray-100', 'text-gray-700');
            });

            document.getElementById(`filter-${status}`).classList.add('bg-blue-100', 'text-blue-700');
            document.getElementById(`filter-${status}`).classList.remove('bg-gray-100', 'text-gray-700');

            // 筛选并渲染订单
            let filteredOrders = allOrders;
            if (status !== 'all') {
                filteredOrders = allOrders.filter(order => order.status === status);
            }
            renderOrders(filteredOrders);
        }

        // 渲染订单列表
        function renderOrders(orders) {
            if (orders.length === 0) {
                orderListElement.innerHTML = `
                    <div class="text-center py-8 text-gray-500">
                        <i class="fas fa-inbox text-4xl mb-2"></i>
                        <p>${currentFilter === 'all' ? '暂无订单数据' : '该状态下暂无订单'}</p>
                    </div>
                `;
                orderListElement.classList.remove('hidden');
                return;
            }
            console.log('orders', orders);

            orderListElement.innerHTML = orders.map(order => {
                const statusInfo = STATUS_MAP[order.status] || { text: '未知状态', class: 'bg-gray-500' };

                let actionButton = '';
                if (order.status === 'GAINED') {
                    actionButton = `
                        <button onclick="location.href='signature.html?orderId=${order.materialCode}'" 
                            class="bg-gradient-to-r from-blue-500 to-indigo-600 text-white py-1 px-3 rounded-lg text-sm font-medium">
                            <i class="fas fa-signature mr-1"></i>签字
                        </button>
                    `;
                } else if (order.status === 'completed') {
                    actionButton = `
                        <button class="text-green-500 text-sm font-medium">
                            <i class="fas fa-download mr-1"></i>下载报告
                        </button>
                    `;
                } else if (order.status === 'test') {
                    actionButton = `
                        <button class="text-blue-500 text-sm font-medium">查看详情</button>
                    `;
                } else if (order.status === 'RETURNED') {
                    actionButton = `
                        <button onclick="location.href='mobile-order-form.html?orderId=${order.materialCode}'" 
                            class="bg-gradient-to-r from-blue-500 to-indigo-600 text-white py-1 px-3 rounded-lg text-sm font-medium">
                            <i class="fas fa-signature mr-1"></i>修改
                        </button>
                    `;
                }

                return `
                    <div class="border border-gray-200 rounded-xl p-4 hover:border-blue-300 transition-all">
                        <div class="flex justify-between items-start mb-2">
                            <h3 class="font-semibold text-gray-800">${order.jcxm || '未知检测项目'}</h3>
                            <span class="${statusInfo.class} text-white text-xs font-medium px-3 py-1 rounded-full">${statusInfo.text}</span>
                        </div>
                        <p class="text-gray-600 text-sm mb-1">委托单位: ${order.wtdw || '未知委托单位'}</p>
                        <p class="text-gray-600 text-sm mb-1">样品名称: ${order.ypmc || '未知样品'}</p>
                        <p class="text-gray-600 text-sm">委托时间: ${order.submitTime || '未知时间'}</p>
                        <div class="flex justify-between items-center mt-3">
                            <span class="text-gray-500 text-xs">送样编号: ${order.sybh || '未知编号'}</span>
                            ${actionButton}
                        </div>
                    </div>
                `;
            }).join('');

            orderListElement.classList.remove('hidden');
        }

        // 显示加载状态
        function showLoading() {
            loadingElement.classList.remove('hidden');
            orderListElement.classList.add('hidden');
            errorElement.classList.add('hidden');
        }

        // 隐藏加载状态
        function hideLoading() {
            loadingElement.classList.add('hidden');
        }

        // 显示错误信息
        function showError(message) {
            errorTextElement.textContent = message;
            errorElement.classList.remove('hidden');
        }
    </script>
</body>

</html>